package pagerank;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class Parser {

	public Parser() {

	}

	public HashMap<String, Page> parse(String fileName) {
		try {
			FileInputStream fstream = new FileInputStream(fileName);
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;

			// ArrayList<Page> pages=new ArrayList<Page>();
			HashMap<String, Page> pages = new HashMap<String, Page>();

			String currentPageId = null;
			ArrayList<String> fLinks = new ArrayList<String>();

			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				if (strLine.matches("^<id>(.*)</id>")) {
					currentPageId = strLine.trim();
					currentPageId = currentPageId.substring(4,
							currentPageId.length() - 5);
					// System.out.println (currentPageId);
				}
				if (strLine.matches("^<links>(.*)</links>")) {
					String line = strLine.trim();
					line = line.substring(7, line.length() - 8);
					String[] tmp = line.split(",");
					for (int i = 0; i < tmp.length; i++) {
						if(!fLinks.contains(tmp[i])){
							fLinks.add(tmp[i]);
						}
					}
					pages.put(currentPageId, new Page(currentPageId, fLinks));
					fLinks = new ArrayList<String>();
				}

			}

			// Close the input stream
			in.close();
			return pages;
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		return null;
	}
}
